export class Cache {

    // 设置缓存
    setCache(key, value, localOrSessionStorage = true) {
        try {
            const val = JSON.stringify(value);
            if (localOrSessionStorage) {
                window.localStorage.setItem(key, val);
            } else {
                window.sessionStorage.setItem(key, val);
            }
            return true;
        } catch (error) {
            console.error("setCache error:", error);
            return false;
        }
    }

    // 获取缓存
    getCache(key, localOrSessionStorage = true) {
        try {
            const storage = localOrSessionStorage ? localStorage : sessionStorage;
            const val = storage.getItem(key);
            return val ? JSON.parse(val) : null;
        } catch (error) {
            console.error("getCache error:", error);
            return null;
        }
    }

    // 删除缓存
    removeCache(key, localOrSessionStorage = true) {
        const storage = localOrSessionStorage ? localStorage : sessionStorage;
        storage.removeItem(key);
    }

    // 清空缓存
    clearCache(localOrSessionStorage = true) {
        const storage = localOrSessionStorage ? localStorage : sessionStorage;
        storage.clear();
    }
}

export default new Cache();
